package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupMapper checkGroupMapper;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //解析分页信息
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //分页
        PageHelper.startPage(currentPage, pageSize);
        Page<CheckGroup> checkGroups = checkGroupMapper.findByCondition(queryString);
        return new PageResult(checkGroups.getTotal(), checkGroups.getResult());
    }

    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        //添加数据
        checkGroupMapper.add(checkGroup);
        Integer checkGroupId = checkGroup.getId();   //获取当前添加的数据的id
        //System.out.println("===========新增检查组id:" + checkGroupId);
        setItemIdAndGroupId(checkGroupId, checkitemIds);

    }

    @Override
    public void setItemIdAndGroupId(Integer checkGroupId, Integer[] checkitemIds) {
        if (checkGroupId != null && checkitemIds.length > 0){
            //添加关联表数据
            for (Integer id : checkitemIds) {
                Map map = new HashMap();
                map.put("checkGroupId",checkGroupId);
                map.put("checkitemId",id);
                checkGroupMapper.setItemIdAndGroupId(map);
            }
        }
    }

    @Override
    public void deleteById(Integer id) {
        //先删除外键关联
        checkGroupMapper.deleteForeignData(id);
        checkGroupMapper.deleteById(id);
    }

    @Override
    public List<Integer> findCheckitemIdsByCheckgroupId(Integer checkgroupId) {
        return checkGroupMapper.findCheckitemIdsByCheckgroupId(checkgroupId);
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //保存更改的基本数据
        checkGroupMapper.edit(checkGroup);
        //获取id
        Integer checkGroupId = checkGroup.getId();
        //删除外键关联
        checkGroupMapper.deleteForeignData(checkGroupId);
        //添加关联数据
        setItemIdAndGroupId(checkGroupId,checkitemIds);
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupMapper.findAll();
    }


}
